package com.hoopchina.ui.details;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlSerializer;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextPaint;
import android.util.Log;
import android.util.Xml;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.GestureDetector.OnGestureListener;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.view.animation.Animation.AnimationListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import com.hoopchina.news.R;
import com.hoopchina.meta.NewsItem;
import com.hoopchina.meta.NewsItemDetail;
import com.hoopchina.meta.NewsItemDetail.Content;
import com.hoopchina.settings.SettingsActivity;
import com.hoopchina.ui.details.FriendlyScrollView;
import com.hoopchina.ui.details.ImageService;
import com.hoopchina.ui.home.GoalHi;
import com.hoopchina.ui.home.HomeView;
import com.hoopchina.ui.home.DragListActivity.DragListAdapter;
import com.hoopchina.ui.main.BaseActivity;
import com.hoopchina.ui.main.NewsListItemView;
import com.hoopchina.ui.main.NewsListView;
import com.hoopchina.ui.main.UIWidget;
import com.hoopchina.ui.main.ViewManager;
import com.hoopchina.ui.search.SearchView;
import com.hoopchina.util.NetUtil;
import com.hoopchina.util.TimeUtils;
import com.hoopchina.util.UrlUtils;
import com.hoopchina.util.download.DownloadCallback;
import com.hoopchina.util.download.DownloadTask;
import com.hoopchina.util.download.Downloader;
import com.hoopchina.util.xml.NewsDetailXML;
import com.hoopchina.util.xml.NewsItemXML;
import com.hoopchina.util.xml.XMLDataNetwork;
import com.hoopchina.weibo.ui.BindingDBEngine;
import com.hoopchina.weibo.ui.ForwardingView;
import com.hoopchina.weibo.ui.WeiboAuthActivity;


//为手势滑动加的
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.OnGestureListener;
import android.view.animation.AnimationUtils;
import android.widget.TextView;
import android.widget.ViewFlipper;

/**
 * 百度新闻详情界面
 * 
 * @author Neusoft
 *
 */
public class DetailsView extends BaseActivity{ 
    public static final String            Id = "DetailsView";
    public static final int   			CONTENT_TEXT_SIZE_MIN = 16;
    public static final int   			CONTENT_TEXT_SIZE_MID= 18;
    public static final int   			CONTENT_TEXT_SIZE_MAX = 20;
	private static final String		PREFS_NAME			= "MyPrefsFile";
    private SharedPreferences mSettings = null;  
    private int  mContentTextSize;
    /** Called when the activity is first created. */  
    private LinearLayout mLayout;
    private LinearLayout mtoolbarLayout;
    private RelativeLayout mtitleLayout;
    private TextView TiTleBarText;
    private Button previousbutton;
    private Button nextbutton;
    private ScrollView sView;
	private boolean mIsFullScreen;
    private LinearLayout mLinearLayout;
    private LinearLayout mContentImageLayout;
    private LinearLayout mContentTextLayout;
    private static List<NewsItem>  mFavoriteNewsList;
    private NewsListView           mListView;
	private final String SAVE_FILE_NAME = "save.xml";
	
	private boolean isShareViewShows = false;
	private boolean isScrolling = false;
	private boolean isNeedrefresh =false;
    
    private final int MESSAGE_NEWDETAILS = 1;
    private final int MSG_LoadingFailed = 2;
    private final int MSG_StrartLoading = 3;
    private final int MSG_RequestFailed = 4;
    private final int MSG_RequestSucessed =5;

    private final int FromMainList = 0; //主列表
    private final int FromFavoritesList = 1; //新闻收藏页
    private final int FromGoalhi = 2; //热门图片
    private final int FromF1 = 3; //桌面4*2插件
    
    private final int TEXTSIZE_MAX = 0;
	private final int TEXTSIZE_MID = 1;
	private final int TEXTSIZE_MIN = 2;
    
    private URLConnection urlConnection;
    private NewsDetailXML mNewsDetailXML = new NewsDetailXML();
    private NewsItemDetail mDetailsinfo = new NewsItemDetail();
    private Content mContentinfo;
    private String mTitle;
    private static int mPosition;
    private static int mHotViewPosition;
    private static int mWidget41NewsPosition;
    private static int mWidget42NewsPosition;
    private static int mGoalHiPosition;
    private static int mF1Position;
    private static int mHotClickPosition;
    private static int mSearchPosition;
    private static int FromType;
    //private String mContent;
    private List<Content> mContent = new ArrayList<Content>();
    private String mImgUrl;
    private String mImageUrl="";
    private String mSource;
    private String mTime;
    private String mUrl;
    private String mAbs;
    private Bitmap imginfo;
    private String mIndex;
    private String mType;
    private String mSubContent;
    private TextView mTextView;
    private TimeUtils SimpleDateFormat = new TimeUtils();
    private final String FILE_PATH = "/sdcard/baidunews/newstempfile/";
    private String info;
    
    private String ContentUrlPrefix = "http://newsmobile.baidu.com/n?m=app&v=detail&url=";
    private String LikeCountUrl = "http://newsmobile.baidu.com/n?m=app&v=like_count&url=http://finance.eastday.com/consumption/m5/20110919/u1a6112154.html";
    
    private ProgressBar mProgressBar;
    private View contentView;
    private ImageView mBaiduNewsLogo;
    
    //手势相关
	private ViewFlipper viewFlipper;;
	private GestureDetector gestureDetector;
	private FriendlyScrollView scroll;	
	private LayoutInflater mInflater;
	private boolean mLoadingShowing = false;
	private FavoritesEngine OperationDB;
	private DetailNewsLikeEngine DetailNewsLikeDB;
	private String NewsType;

    //设置图片的缓冲区
    private static final int IO_BUFFER_SIZE = 4 * 1024;
    
	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case MESSAGE_NEWDETAILS:
				SetDetailsView(contentView);
				break;
			case MSG_LoadingFailed:
				// Toast.makeText(mViewManager.getCurrentActivity(),
				// "载入失败，请核查网络...", Toast.LENGTH_SHORT ).show();
				Toast.makeText(mViewManager.getCurrentActivity(),
						getString(R.string.details_loadingfailed),
						Toast.LENGTH_SHORT).show();
				mBaiduNewsLogo.setVisibility(View.VISIBLE);
				mProgressBar.setVisibility(View.GONE);
				break;

			case MSG_StrartLoading:
				showBaiduNewsLogo(true);
				break;
			case MSG_RequestFailed:
				Toast.makeText(mViewManager.getCurrentActivity(),
						getString(R.string.likeinfo_requestfailed),
						Toast.LENGTH_SHORT).show();
				break;
			case MSG_RequestSucessed:
				Cursor cursor = DetailNewsLikeDB.queryByUrl(mUrl);
				long currentTimeSec= System.currentTimeMillis()/1000;			
				if (cursor.getCount() == 0) {
					DetailNewsLikeDB.insert(mUrl, String.valueOf(currentTimeSec));
					Toast.makeText(mViewManager.getCurrentActivity(),
							info, Toast.LENGTH_SHORT).show();
				}else{
					Toast.makeText(mViewManager.getCurrentActivity(),
							getString(R.string.details_Like_info), Toast.LENGTH_SHORT).show();
				} 
				cursor.close();
			default:
				break;
			}
		}
};
    
    @Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mSettings = getSharedPreferences(PREFS_NAME, 0);
		setContentView(R.layout.detailsview);
		mViewManager.setTabBarVisibility(false);
		OperationDB = new FavoritesEngine(this);
		DetailNewsLikeDB = new DetailNewsLikeEngine(this);
		mSettings = getSharedPreferences(PREFS_NAME, 0);
		
		Log.i("Details", "onCreate");
		// 初始化UI
		Bundle intent = getIntent().getExtras();
		
		if ( intent == null ){
			return;
		}

		// 很多View都会跳转到详情页。为了区分我们给每个可以跳转来得页面都分配了一个Type
		// 主列表是 0
		// 收藏页是 1
		// 热门图片是 2
		// widget4*2是 3
		//
		FromType = intent.getInt("Type");
		if (FromType == FromMainList) {
			mPosition = intent.getInt("NewPosition") - 1;
		} else if (FromType == FromGoalhi) {
			mGoalHiPosition = intent.getInt("NewPosition");
		}else if (FromType == FromF1 ){
			mF1Position = intent.getInt("HotSharePosition");
		}

		viewFlipper = (ViewFlipper) findViewById(R.id.viewflipper_data);
		mInflater = LayoutInflater.from(this);
		gestureDetector = new GestureDetector(new CommonGestureListener());
		TiTleBarText = (TextView) findViewById(R.id.TitleBarTitle);
		previousbutton = (Button) findViewById(R.id.previousbutton);
		nextbutton = (Button) findViewById(R.id.nextbutton);

		viewFlipper.addView(getContentView());

		mMyHandleBackButton = true;
		
		if (mSettings == null
				|| mSettings.getBoolean("user_guide_details", true)) {
			mViewManager
					.setUserGuideImage(R.drawable.image_guide_news_details_view);
			mViewManager.setUserGuideOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					SharedPreferences.Editor editor = mSettings.edit();
					editor.putBoolean("user_guide_details", false);
					editor.commit();
					mViewManager.setUserGuideVisibility(ImageButton.GONE);

				}
			});
			mViewManager.setUserGuideVisibility(ImageButton.VISIBLE);
		} else {
			mViewManager.setUserGuideVisibility(ImageButton.GONE);

		}
		
	}
    /**
     * 存储阅读状态
     */
    public void saveReadStatus(String title,String time){
    	String deitailMarker=UrlUtils.getNameFromUrl(title.trim()+time.trim());
		//保存点击状态
		Editor editor=mSettings.edit();
		editor.putBoolean(deitailMarker, true);
		editor.commit();
    }
    
    
    /** 
     *  初始化阅读正文页
     */  
	private View getContentView() {
		// contentView = new View(this);
	    
        if ( null == mInflater )
            mInflater = LayoutInflater.from( this );

		contentView = mInflater.inflate(R.layout.common_info_item_view, null);

		mBaiduNewsLogo = (ImageView) contentView
				.findViewById(R.id.baidunewslogo);
		mProgressBar = (ProgressBar) contentView
				.findViewById(R.id.progressBarLoadingDetailView);

		sView = (ScrollView) contentView.findViewById(R.id.detailScrollView);
		//sView.setScrollbarFadingEnabled(true);
		TextView TitleTextView = (TextView) contentView
				.findViewById(R.id.NewsTitleText);
		TextView TimeAndSourceTextView = (TextView) contentView
				.findViewById(R.id.NewsTimeAndSource);
		ImageView slimage = (ImageView) contentView
				.findViewById(R.id.separateline);

//		TextPaint tp = TitleTextView.getPaint();
//		tp.setFakeBoldText(true);
		Bundle intent = getIntent().getExtras();
		if ( intent == null ){
			return contentView;
		}

		switch (FromType) {
		case FromMainList:
			// 从主列表获取获取新闻类型
			NewsType = intent.getString("NewsType");
			String pageCount = String.valueOf(mPosition);
			Log.i("mPosition", pageCount);

			if ( HomeView.mNewsList==null ||HomeView.mNewsList.size()<=mPosition )
			{return contentView;}
			mTitle = HomeView.mNewsList.get(mPosition).getTitle();
			mSource = HomeView.mNewsList.get(mPosition).getAuthor();
			mTime = HomeView.mNewsList.get(mPosition).getTime();
			mAbs = HomeView.mNewsList.get(mPosition).getAbs();
			mImgUrl = HomeView.mNewsList.get(mPosition).getImgUrl();
			mUrl = HomeView.mNewsList.get(mPosition).getUrl().trim();
			//mViewManager.setTitle(NewsType);
			TiTleBarText.setText(NewsType);
			saveReadStatus(mTitle, mTime);
			break;
		case FromGoalhi:
			// 从主列表获取获取新闻类型
			NewsType = intent.getString("NewsType");
			//String pageCount = String.valueOf(mPosition);
			//Log.i("mPosition", pageCount);

			if ( GoalHi.mNewsList==null ||GoalHi.mNewsList.size()<=mPosition )
			{return contentView;}
			mTitle = GoalHi.mNewsList.get(mPosition).getTitle();
			mSource = GoalHi.mNewsList.get(mPosition).getAuthor();
			mTime = GoalHi.mNewsList.get(mPosition).getTime();
			mAbs = GoalHi.mNewsList.get(mPosition).getAbs();
			mImgUrl = GoalHi.mNewsList.get(mPosition).getImgUrl();
			mUrl = GoalHi.mNewsList.get(mPosition).getUrl().trim();
			//mViewManager.setTitle(NewsType);
			TiTleBarText.setText(NewsType);
			saveReadStatus(mTitle, mTime);
			break;
		case FromFavoritesList:
			mTitle = intent.getString("title");
			mSource = intent.getString("Author");
			mTime = intent.getString("time");
			mImgUrl = intent.getString("ImageUrl");
			mUrl = intent.getString("Url").trim();
			mAbs = intent.getString("Abs");
			TiTleBarText.setText(getString(R.string.favorates_Title));
			break;
		default:
			break;
		}

		TitleTextView.setText(mTitle.trim());
		TitleTextView.setTextSize(18);

		TimeAndSourceTextView.setText(TimeUtils.getDetailDate(mTime)
				+"    " + getString(R.string.details_from)+"    " + mSource);
		TimeAndSourceTextView.setTextSize(12);
		slimage.setVisibility(View.VISIBLE);
		
		// 判断是否当前新闻已经收藏
		Cursor cursor = OperationDB.queryByTitle(mTitle);
		if (cursor.getCount() == 0) {
			((Button) findViewById(R.id.favoritesButton))
					.setBackgroundResource(R.drawable.image_toolbar_button_favorites);
		} else {
			((Button) findViewById(R.id.favoritesButton))
					.setBackgroundResource(R.drawable.image_toolbar_button_favorites_remove);
		}
		cursor.close();

		if ( !UrlUtils.getFileFromUrl( FILE_PATH , ContentUrlPrefix + mUrl ).exists()) {
			Downloader.getInstance().download(ContentUrlPrefix + mUrl,
					FILE_PATH, new DownloadCallback() {
						@Override
						public void onFinished(DownloadTask finishedTask) {

						}

						@Override
						public void onFailed() {

						}
					});

			if ( CheckNetwork() ) {
				initNewsDetails(ContentUrlPrefix + mUrl, contentView);
			} else {
				//showBaiduNewsLogo(true);
				mBaiduNewsLogo.setVisibility(View.VISIBLE);
			}

		} else {
			 InputStream instreamChannelInfo = null;
			 try {
			 instreamChannelInfo = new
			 FileInputStream( UrlUtils.getFileFromUrl( FILE_PATH , ContentUrlPrefix + mUrl ) );//("/sdcard/baidunews/newstempfile/detail.xml");
			 } catch (FileNotFoundException e) {
			 e.printStackTrace();
			 }
			
			 mDetailsinfo = mNewsDetailXML.getNewsList( instreamChannelInfo );
			 SetDetailsView(contentView);
//			InputStream instreamChannelInfo = null;
//			instreamChannelInfo = this.getClass().getClassLoader()
//					.getResourceAsStream("detail.xml");
//
//			mDetailsinfo = mNewsDetailXML.getNewsList(instreamChannelInfo);
//			SetDetailsView(contentView);
		}

		scroll = (FriendlyScrollView) contentView
				.findViewById(R.id.detailScrollView);
		scroll.setOnTouchListener(onTouchListener);
		scroll.setGestureDetector(gestureDetector);

		return contentView;
	}
	
    /** 
     *  检查网络
     */
	private boolean CheckNetwork() {
		boolean flag = false;
		ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		if (cwjManager.getActiveNetworkInfo() != null)
			flag = cwjManager.getActiveNetworkInfo().isAvailable();
		return flag;
	} 
	
	
    
    /** 
     * 显示新闻正文图片
     */  
	private void showBaiduNewsLogo(boolean isshow) {
		if (isshow) {
			mBaiduNewsLogo.setVisibility(View.VISIBLE);
			mProgressBar.setVisibility(View.VISIBLE);
			viewFlipper.setClickable(false);
			//mLoadingShowing = true;
		} else {
			mBaiduNewsLogo.setVisibility(View.GONE);
			mProgressBar.setVisibility(View.GONE);
			viewFlipper.setClickable(true);
			mLoadingShowing = false;
		}

	}
    
    /** 
     * 设置新闻阅读正文
     */  
	private void SetDetailsView(View mView) {
		if (mDetailsinfo == null) {
			return;
		}
		// mTitle = mDetailsinfo.getTitle();
		// mSource = mDetailsinfo.getSource();
		// mTime = mDetailsinfo.getTime();
		// mUrl = mDetailsinfo.getUrl();

		View mcontentView = mView;

		mLayout = (LinearLayout) mcontentView.findViewById(R.id.LinearLayout);
		mtoolbarLayout = (LinearLayout) findViewById(R.id.toolBarLinearLayout);
		mtitleLayout = (RelativeLayout) findViewById(R.id.titlebar);
		mLinearLayout = (LinearLayout) mcontentView
				.findViewById(R.id.LinearLayout);

		// 创建一个ScrollView对象
		sView = (ScrollView) contentView.findViewById(R.id.detailScrollView);
		TextView TitleTextView = (TextView) contentView
				.findViewById(R.id.NewsTitleText);

		// 设置新闻Title为黑体
//		TextPaint tp = TitleTextView.getPaint();
//		tp.setFakeBoldText(true);
		final Button favoritesButton = (Button) findViewById(R.id.favoritesButton);

		// 设置正文字体大小
		SharedPreferences appSettings = PreferenceManager
				.getDefaultSharedPreferences(this);
		String textSize = appSettings.getString(
				"settings_text_size",
				getResources().getString(
						R.string.settings_text_size_default_value));
		if (textSize.equalsIgnoreCase("大")) {
			mContentTextSize = CONTENT_TEXT_SIZE_MAX;
		} else if (textSize.equalsIgnoreCase("小")) {
			mContentTextSize = CONTENT_TEXT_SIZE_MIN;
		} else {
			mContentTextSize = CONTENT_TEXT_SIZE_MID;
		}

		// TitleTextView.setText(mTitle);
		// TitleTextView.setTextSize(18);
		// TimeAndSourceTextView.setText( SimpleDateFormat.formatTime(mTime) +
		// "      来自: "+mSource);
		// TimeAndSourceTextView.setTextSize(12);
		// slimage.setVisibility(View.VISIBLE);

		// 动态创建新闻图片和正文区域
		mContent = mDetailsinfo.getContent();
		if ( mContent.size() != 0  ){
			for (int i = 0; i < mContent.size(); i++) {
				Content c = mContent.get(i);
				mType = c.getType();
				mSubContent = c.getSubContent();

				if (mType.equalsIgnoreCase("image")) {
					final ImageView imageView = new ImageView(this);
					LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
							LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
					param.topMargin = dip2px(this,10);//10;
					param.rightMargin = dip2px(this,14);//14;
					param.leftMargin = dip2px(this,14);//14;
					showImage(imageView, mSubContent);
					if(mImageUrl.equals(""))
					{
						mImageUrl = mSubContent;
						Log.i("DetailsView","mImageUrl="+mImageUrl);
					}
					mLinearLayout.addView(imageView, param);
				} else if (mType.equalsIgnoreCase("text")) {
					mTextView = new TextView(this);
					LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
							LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
					param.topMargin = dip2px(this,12);//14;
					param.rightMargin = dip2px(this,14);//14;
					param.leftMargin = dip2px(this,14);//14;

					mTextView.setText("        " + mSubContent.trim());

					mTextView.setTextSize(mContentTextSize);
					mTextView.setTextColor(Color.parseColor("#2b2b2b"));
					mLinearLayout.addView(mTextView, param);
				}
			}
			final ImageView BottomImageView = new ImageView(this);
			LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			param.bottomMargin = dip2px(this,14);//20;
			mLinearLayout.addView(BottomImageView, param);
			showBaiduNewsLogo(false);			
		}else{
			mBaiduNewsLogo.setVisibility(View.VISIBLE);
			mProgressBar.setVisibility(View.GONE);
		}

		mViewManager.setTabBarVisibility(false);

		((Button) findViewById(R.id.transferButton))
				.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						Log.i("onContextItemSelected", "1");
						final CharSequence[] items = { 	             		 
								getResources().getString(R.string.forward_select_item_sina)
			               		, getResources().getString(R.string.forward_select_item_tencent)
			               		, getResources().getString(R.string.forward_select_item_sohu)
			               		, getResources().getString(R.string.forward_select_item_netease)
			               		, getResources().getString(R.string.forward_select_item_renren)};
						AlertDialog.Builder builder = new AlertDialog.Builder(
								DetailsView.this);
						builder.setTitle(getResources().getString(R.string.forward_select_dialog_title));

						builder.setItems(items,
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int item) {
						        		if (!NetUtil.checkNet(DetailsView.this)) {
						        			Toast.makeText(mViewManager.getCurrentActivity(),
						        					getResources().getString(R.string.app_no_network),
						        					Toast.LENGTH_SHORT).show();
						        		}
						        		else
						        		{
											Bundle aBundle = new Bundle();
											aBundle.putInt("WeiboType", item);
											aBundle.putString("Title", mTitle);
											aBundle.putBoolean("FromBindingPage",
													false);

											aBundle.putString("ImageUrl", mImageUrl);
											aBundle.putString("NewsUrl", mUrl);
											aBundle.putString("Abstract", mAbs);
											aBundle.putString("Author", mSource);
											BindingDBEngine mEngine = new BindingDBEngine(
													DetailsView.this);
											if (mEngine.isBinding(item)) {
												ForwardingView
														.setOldView(DetailsView.Id,DetailsView.class);
												ViewManager
														.getInstance()
														.showClearOnTopView(
																ForwardingView.Id,
																ForwardingView.class,
																false, aBundle);
											} else {
												WeiboAuthActivity
														.setOldView(DetailsView.Id,DetailsView.class);
												ViewManager
														.getInstance()
														.showClearOnTopView(
																WeiboAuthActivity.Id,
																WeiboAuthActivity.class,
																false, aBundle);
											}
						        		}
									}
								});
						builder.create().show();
					}
				});

		// 好感按钮按键监听
		((Button) findViewById(R.id.likeButton))
				.setOnClickListener(new OnClickListener() {
					@Override
				public void onClick(View arg0) {
//						String currentTimeSec= String.valueOf( System.currentTimeMillis()/1000 );
//						DetailNewsLikeDB.delete(currentTimeSec);
//						
//						new Thread() {
//							public void run() {
//								try {
//								urlConnection = XMLDataNetwork
//										.getHttpConnection(LikeCountUrl);
//							} catch (IOException e) {
//								mHandler.sendEmptyMessage(MSG_RequestFailed);
//							}
//					
//					try {
//						mLikeCount = mNewsLikeXML.getLikeCount(urlConnection
//								.getInputStream());
//						int LikeCount = Integer.valueOf(mLikeCount.getLikeCount());
//						info = "好感度 + 1，已有"+String.valueOf(LikeCount)+"人喜欢本新闻";
//						mHandler.sendEmptyMessage(MSG_RequestSucessed);
//					} catch (IOException e) {
//						mHandler.sendEmptyMessage(MSG_RequestFailed);
//					}
//							}
//						}.start();
				}
				});

		// 收藏按钮按键监听
		((Button) findViewById(R.id.favoritesButton))
				.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						Cursor cursor = OperationDB.queryByTitle(mTitle);
						if (cursor.getCount() == 0) {
							Toast.makeText(DetailsView.this,
									getString(R.string.app_save_sucess), 100)
									.show();
							((Button) findViewById(R.id.favoritesButton))
									.setBackgroundResource(R.drawable.image_toolbar_button_favorites_remove);
							AddToFavorites();
						} else {
							Toast.makeText(DetailsView.this,
									getString(R.string.app_remove_sucess), 100)
									.show();
							((Button) findViewById(R.id.favoritesButton))
									.setBackgroundResource(R.drawable.image_toolbar_button_favorites);
							DeleteInFavorites();
						}
						cursor.close();
					}
				});

		// 分享按钮按键监听
		((Button) findViewById(R.id.shareButton))
				.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						isShareViewShows = true;
						mViewManager.setTabBarVisibility(false);
						Intent intent = new Intent(Intent.ACTION_SEND);
						intent.setType("text/plain");
						intent.putExtra(Intent.EXTRA_SUBJECT, "分享");
						intent.putExtra(Intent.EXTRA_TEXT, mTitle + mUrl
								+ getString(R.string.details_from_Baidu_share));
						mViewManager.setTabBarVisibility(false);
						startActivity(Intent.createChooser(intent, getTitle()));
						mViewManager.setTabBarVisibility(false);
					}
				});

		// 源新闻按钮按键监听
		((Button) findViewById(R.id.sourceButton))
				.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						mViewManager.setTabBarVisibility(false);
						Uri uri = Uri.parse(mUrl);
						Intent intent = new Intent(Intent.ACTION_VIEW, uri);
						intent.setClassName("com.android.browser",
								"com.android.browser.BrowserActivity");
						mViewManager.setTabBarVisibility(false);
						startActivity(intent);

					}
				});
	}
	
	/**

	* 根据手机的分辨率从 dip 的单位 转成为 px(像素)

	*/	
	public static int dip2px(Context context, float dipValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dipValue * scale + 0.5f);
}
    
	private void showImage(final ImageView imageView, final String aUrl) {
		Drawable aDrawable = Downloader.getInstance().DownloadDrawable(
				getCacheDir().toString(), aUrl,getApplicationContext(),0,
				new Downloader.DrawableDownloadCallback() {

					@Override
					public void drawableDownloaded(Drawable imageDrawable,
							Object tag) {
						if (imageView != null) {
							imageView.setImageDrawable(imageDrawable);
						}
					}
				});

		if (aDrawable != null) {
			imageView.setImageDrawable(aDrawable);
		} else {
			// set default resource
			// imageView.setImageResource();
		}
	}
    
    /* 
     * 添加新闻到我的收藏页
     */  
    private void AddToFavorites(){
    	OperationDB.insert(mUrl, mTitle, mAbs, mSource, mTime,mImgUrl);
    }
    

    /** 
     * 删除收藏的新闻
     */     
    private void DeleteInFavorites(){
    	OperationDB.delete(mTitle);
    }
    
	private void initNewsDetails(final String url, View mView) {
		new Thread() {
			public void run() {
				try {
					String contentUrl = url;
					Log.i("获取到的地址", contentUrl);
					urlConnection = XMLDataNetwork
							.getHttpConnection(contentUrl);
				} catch (SocketTimeoutException e) {
					mHandler.sendEmptyMessage(MSG_LoadingFailed);
					return;
				} catch (MalformedURLException e) {
					mHandler.sendEmptyMessage(MSG_LoadingFailed);
					return;
				} catch (IOException e) {
					mHandler.sendEmptyMessage(MSG_LoadingFailed);
					return;
				}

				mHandler.sendEmptyMessage(MSG_StrartLoading);
				try {
					mDetailsinfo = mNewsDetailXML.getNewsList(urlConnection
							.getInputStream());
				} catch (IOException e) {
					mHandler.sendEmptyMessage(MSG_LoadingFailed);
					return;
				}

				if (mDetailsinfo == null) {
					mHandler.sendEmptyMessage(MSG_LoadingFailed);
				}
				mHandler.sendEmptyMessage(MESSAGE_NEWDETAILS);
			}
		}.start();

	}

	private void onAnimfullScream() {
		mIsFullScreen = true;
		mViewManager.doAnimOnTitleBar(mIsFullScreen);
		doAnimOnToolBar(mIsFullScreen);
		doAnimOnDetailView(mIsFullScreen);
	} 
    
    /** 
     * 设置标题栏和工具栏是否显示
     */  
	private void toggleAnimfullScream() {
		mIsFullScreen = !mIsFullScreen;
		//mViewManager.doAnimOnTitleBar(!mIsFullScreen);3
		doAnimOnTitleBar(!mIsFullScreen);
		//mtitleLayout.setAnimation(AnimationControl.inFromDownAnimation());
		doAnimOnToolBar(!mIsFullScreen);
		//doAnimOnDetailView(!mIsFullScreen);
	}
	
    /** 
     * 设置工具栏是否显示
     */  
    public void doAnimOnTitleBar( boolean aEnabled ) {
    	AnimationSet titleBarAnimSet = null;
    	
    	if ( null == mtitleLayout ) {
            Log.e( "error", "null == mtitleLayout" );
            return;
        }
    	
    	if ( aEnabled ) {
    		mtitleLayout.setVisibility( View.VISIBLE );
	    	titleBarAnimSet = createTitleBarAnim( 
	    			0, 0, -mtitleLayout.getHeight(), 5,
	    			0, 1, null, true );
	    	//sView.setAnimation(AnimationControl.inFromDownAnimation());
    	}
    	else {
    		titleBarAnimSet = createTitleBarAnim( 
    			0, 0, 5, -mtitleLayout.getHeight(),
    			1, 0, mtitleLayout, false );
    	}
    	mtitleLayout.startAnimation( titleBarAnimSet );
    	//sView.setAnimation(AnimationControl.outToUpAnimation());
    }
    
    /** 
     * 设置工具栏是否显示
     */  
    public void doAnimOnDetailView( boolean aEnabled ) {
    	AnimationSet DetailViewAnimSet = null;
		if ( null == mLinearLayout ) {
            Log.e( "error", "null == mtitleLayout" );
            return;
        }
    	if ( aEnabled ) {
    		DetailViewAnimSet = createAnim( 
	    			0, 0, -mtitleLayout.getHeight(), 5,
	    			0, 1, null, true );
    	}
    	else {
    		DetailViewAnimSet = createAnim( 
    			0, 0, 5, -mtitleLayout.getHeight(),
    			1, 0, null, false );
    	}
    	mLinearLayout.startAnimation( DetailViewAnimSet );
    }
    
    /** 
     * 设置工具栏是否显示
     */  
	private void doAnimOnToolBar(boolean aEnabled) {
		AnimationSet toolBarAnimSet = null;
		if ( null == mtoolbarLayout ) {
            Log.e( "error", "null == mtoolbarLayout" );
            return;
        }
		
		if (aEnabled) {
			mtoolbarLayout.setVisibility(View.VISIBLE);
			toolBarAnimSet = createAnim(0, 0, mtoolbarLayout.getHeight(), -5,
					0, 1, null, true);
		} else {
			toolBarAnimSet = createAnim(0, 0, -5, mtoolbarLayout.getHeight(),
					1, 0, mtoolbarLayout, false);
		}
		mtoolbarLayout.startAnimation(toolBarAnimSet);
	}
    
    /** 
     * 详情页工具栏的动画效果
     */ 
	private AnimationSet createAnim(int aX1, int aX2, int aY1, int aY2,
			float alpha1, float alpha2, final LinearLayout atoolBarAnimSet,
			final boolean aVisible) {
		AnimationSet animSet = new AnimationSet(false);
		TranslateAnimation transAnim = new TranslateAnimation(aX1, aX2, aY1,
				aY2);
		animSet.addAnimation(transAnim);
		AlphaAnimation alphaAnim = new AlphaAnimation(alpha1, alpha2);
		animSet.addAnimation(alphaAnim);
		animSet.setDuration(400);
		if (atoolBarAnimSet != null) {
			animSet.setAnimationListener(new AnimationListener() {
				@Override
				public void onAnimationEnd(Animation animation) {
					atoolBarAnimSet.setVisibility(aVisible ? View.VISIBLE
							: View.GONE);
				}

				@Override
				public void onAnimationRepeat(Animation animation) {
				}

				@Override
				public void onAnimationStart(Animation animation) {
				}
			});
		}
		return animSet;
	}
	
    /** 
     * 详情页标题栏的动画效果
     */ 
	private AnimationSet createTitleBarAnim(int aX1, int aX2, int aY1, int aY2,
			float alpha1, float alpha2, final RelativeLayout atoolBarAnimSet,
			final boolean aVisible) {
		AnimationSet animSet = new AnimationSet(false);
		TranslateAnimation transAnim = new TranslateAnimation(aX1, aX2, aY1,
				aY2);
		animSet.addAnimation(transAnim);
		AlphaAnimation alphaAnim = new AlphaAnimation(alpha1, alpha2);
		animSet.addAnimation(alphaAnim);
		animSet.setDuration(400);
		if (atoolBarAnimSet != null) {
			animSet.setAnimationListener(new AnimationListener() {
				@Override
				public void onAnimationEnd(Animation animation) {
					atoolBarAnimSet.setVisibility(aVisible ? View.VISIBLE
							: View.GONE);
				}

				@Override
				public void onAnimationRepeat(Animation animation) {
				}

				@Override
				public void onAnimationStart(Animation animation) {
				}
			});
		}
		return animSet;
	}
    
    
    @Override
	public void onResume() {
		super.onResume();
		if ( !((RelativeLayout) findViewById(R.id.titlebar)).isShown() ){
			((RelativeLayout) findViewById(R.id.titlebar)).setVisibility(View.VISIBLE);
		}		
		isShareViewShows =false;
		mViewManager.showDetailViewBar(true);
		mViewManager.setTitleBarVisibility(false);
		mViewManager.setTabBarVisibility(false);
		previousbutton = (Button) findViewById(R.id.previousbutton);
		nextbutton = (Button) findViewById(R.id.nextbutton);

		if (FromType == FromMainList) {
			if (mPosition == 0) {
				//mViewManager.showPreButton(false);
				previousbutton.setVisibility(View.INVISIBLE);
			}

			if (mPosition == HomeView.mNewsList.size() - 1) {
				//mViewManager.showNextButton(false);
				nextbutton.setVisibility(View.INVISIBLE);
			}
		}
		 else if (FromType == FromFavoritesList) {
//			mViewManager.showNextButton(false);
//			mViewManager.showPreButton(false);
			previousbutton.setVisibility(View.INVISIBLE);
			nextbutton.setVisibility(View.INVISIBLE);
		}

		// 设置详情页TitleBar，新闻上下页查看按钮监听			
		previousbutton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// mViewManager.showNextButton(true);
				nextbutton.setVisibility(View.VISIBLE);
				HandleShowPreviousNews();
			}
		});

		nextbutton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// mViewManager.showPreButton(true);
				previousbutton.setVisibility(View.VISIBLE);
				HandleShowNextNews();

			}
		});

	}
  
    /** 
     * 设置新闻正文字体大小
     * 
     */ 
	private void ResetNewsContentTextSize() {
		// 设置正文字体大小
		SharedPreferences appSettings = PreferenceManager
				.getDefaultSharedPreferences(this);
		String textSize = appSettings.getString(
				"settings_text_size",
				getResources().getString(
						R.string.settings_text_size_default_value));
		if (textSize.equalsIgnoreCase("大")) {
			mContentTextSize = CONTENT_TEXT_SIZE_MAX;
		} else if (textSize.equalsIgnoreCase("小")) {
			mContentTextSize = CONTENT_TEXT_SIZE_MIN;
		} else {
			mContentTextSize = CONTENT_TEXT_SIZE_MID;
		}
		
		for (int i = 3; i< mLinearLayout.getChildCount(); i++) {
			Object obj = mLinearLayout.getChildAt(i);
			if(obj instanceof TextView) {
				((TextView)obj).setTextSize(mContentTextSize) ;
			}
		}
	}

    /** 
     * 刷新当前页面
     * 
     */ 
	private void RefreshDetailsView(View mView) {
		contentView = mView;
			mBaiduNewsLogo = (ImageView) contentView
					.findViewById(R.id.baidunewslogo);
			mProgressBar = (ProgressBar) contentView
					.findViewById(R.id.progressBarLoadingDetailView);

			if (!UrlUtils.getFileFromUrl(FILE_PATH, ContentUrlPrefix + mUrl)
					.exists()) {
				Downloader.getInstance().download(ContentUrlPrefix + mUrl,
						FILE_PATH, new DownloadCallback() {
							@Override
							public void onFinished(DownloadTask finishedTask) {

							}

							@Override
							public void onFailed() {

							}
						});

				if (CheckNetwork()) {
					initNewsDetails(ContentUrlPrefix + mUrl, contentView);
				} else {
					// showBaiduNewsLogo(true);
					mBaiduNewsLogo.setVisibility(View.VISIBLE);
				}

			} else {
				InputStream instreamChannelInfo = null;
				try {
					instreamChannelInfo = new FileInputStream(
							UrlUtils.getFileFromUrl(FILE_PATH, ContentUrlPrefix
									+ mUrl));
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}

				mDetailsinfo = mNewsDetailXML.getNewsList(instreamChannelInfo);

				// 设置正文字体大小
				SharedPreferences appSettings = PreferenceManager
						.getDefaultSharedPreferences(this);
				String textSize = appSettings.getString(
						"settings_text_size",
						getResources().getString(
								R.string.settings_text_size_default_value));
				if (textSize.equalsIgnoreCase("大")) {
					mContentTextSize = CONTENT_TEXT_SIZE_MAX;
				} else if (textSize.equalsIgnoreCase("小")) {
					mContentTextSize = CONTENT_TEXT_SIZE_MIN;
				} else {
					mContentTextSize = CONTENT_TEXT_SIZE_MID;
				}

				// 动态创建新闻图片和正文区域
				mContent = mDetailsinfo.getContent();
				if (mContent.size() != 0) {
					for (int i = 0; i < mContent.size(); i++) {
						Content c = mContent.get(i);
						mType = c.getType();
						mSubContent = c.getSubContent();

						if (mType.equalsIgnoreCase("image")) {
							final ImageView imageView = new ImageView(this);
							LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
									LayoutParams.WRAP_CONTENT,
									LayoutParams.WRAP_CONTENT);
							param.topMargin = dip2px(this,10);//10;
							param.rightMargin = dip2px(this,14);//14;
							param.leftMargin = dip2px(this,14);//14;
							showImage(imageView, mSubContent);

							mImgUrl = mSubContent;
							mLinearLayout.addView(imageView, param);
						} else if (mType.equalsIgnoreCase("text")) {
							final TextView mTextView = new TextView(this);
							LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
									LayoutParams.WRAP_CONTENT,
									LayoutParams.WRAP_CONTENT);
							param.topMargin = dip2px(this,12);//14;
							param.rightMargin = dip2px(this,14);//14;
							param.leftMargin = dip2px(this,14);//14;

							mTextView.setText(mSubContent);

							mTextView.setTextSize(mContentTextSize);
							mTextView.setTextColor(Color.parseColor("#2b2b2b"));
							mLinearLayout.addView(mTextView, param);
						}
					}
					final ImageView BpttomImageView = new ImageView(this);
					LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
							LayoutParams.WRAP_CONTENT,
							LayoutParams.WRAP_CONTENT);
					param.bottomMargin = dip2px(this,14);//20;
					mLinearLayout.addView(BpttomImageView, param);
					showBaiduNewsLogo(false);
				} else {
					mBaiduNewsLogo.setVisibility(View.VISIBLE);
					mProgressBar.setVisibility(View.GONE);
				}
			}

		}
  
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		menu.clear();
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.detailview, menu);
		return true;

	}
	
//    /** 
//     * 返回键事件处理
//     * 
//     */ 
//	public boolean onKeyDown(int keyCode, KeyEvent event) {
//		//从详情页切换到别的页面的时候，隐藏详情页的标题栏。防止很明显的闪烁。
//		if (keyCode == KeyEvent.KEYCODE_BACK) {
//			((RelativeLayout) findViewById(R.id.titlebar)).setVisibility(View.INVISIBLE);
//			return super.onKeyDown(keyCode, event);
//		} else {
//			return super.onKeyDown(keyCode, event);
//		}
//	}
	
  @Override
  public boolean onOptionsItemSelected( MenuItem item ) {
      switch (item.getItemId()) {
      case R.id.menu_detailview_refresh:
    	  isNeedrefresh = true;
  		if (mLinearLayout != null && mLinearLayout.getChildCount() > 3) {
			String mcontent = null;
			for (int i = 3; i< mLinearLayout.getChildCount(); i++) {
				Object obj = mLinearLayout.getChildAt(i);
				if(obj instanceof TextView) {
					mcontent = ((TextView)obj).getText().toString();
				}
			}
			if (  mcontent.equals("") && UrlUtils.getFileFromUrl(FILE_PATH, ContentUrlPrefix + mUrl)
					.exists()){
				   UrlUtils.getFileFromUrl(FILE_PATH, ContentUrlPrefix + mUrl).delete();
				   RefreshDetailsView(viewFlipper.getCurrentView());
			}else {
				//DoNothing
			}
  		}else{
			RefreshDetailsView(viewFlipper.getCurrentView());
  		}
			Log.i("Menu", "====> Refresh");
    	  break;
          case R.id.menu_detailview_font:	  
        	final  String[] textSizes = this.getResources().getStringArray(R.array.a_settings_text_sizes);
              SharedPreferences appSettings = PreferenceManager.getDefaultSharedPreferences(this);
              String textSize = appSettings.getString("settings_text_size", getResources().getString(R.string.settings_text_size_default_value));
              if ( textSize.equalsIgnoreCase("大") )
              {
             	 mContentTextSize = TEXTSIZE_MAX;
              }else if ( textSize.equalsIgnoreCase("小") )
              {
             	 mContentTextSize = TEXTSIZE_MIN;
              }
              else
              {
             	 mContentTextSize = TEXTSIZE_MID;
              }
              
        	  new AlertDialog.Builder(DetailsView.this).setTitle(DetailsView.this.getString(R.string.app_settings_item_title_text_size)).setIcon(android.R.drawable.ic_dialog_info).setSingleChoiceItems(
        			  textSizes, mContentTextSize, 
        			  new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							
							  SharedPreferences appSettings = PreferenceManager.getDefaultSharedPreferences(DetailsView.this);
							  SharedPreferences.Editor editor = appSettings.edit();
							  editor.putString( "settings_text_size", textSizes[which] );
							  editor.commit();
							dialog.dismiss();
									ResetNewsContentTextSize();
						}
					}).setNegativeButton("取消", null).show();
        	  
    
    
              break;


		case R.id.menu_detailview_my_favorites:
			Bundle bundle = new Bundle();
			bundle.putString("LaunchType", "FromDetailMenu");
			((RelativeLayout) findViewById(R.id.titlebar)).setVisibility(View.INVISIBLE);
			mViewManager.getInstance().showClearOnTopView(MyFavoritesView.Id,
					MyFavoritesView.class, true, bundle);
			mViewManager.setTabBarVisibility(false);
			break;
		case R.id.menu_detail_user_guide:
			if ( mIsFullScreen )
				toggleAnimfullScream();
			mViewManager
					.setUserGuideImage(R.drawable.image_guide_news_details_view);
			mViewManager.setUserGuideOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					SharedPreferences.Editor editor = mSettings.edit();
					editor.putBoolean("user_guide_details", false);
					editor.commit();
					mViewManager.setUserGuideVisibility(ImageButton.GONE);

				}
			});
			mViewManager.setUserGuideVisibility(ImageButton.VISIBLE);

			break;

		case R.id.menu_detailview_settings:
			((RelativeLayout) findViewById(R.id.titlebar)).setVisibility(View.INVISIBLE);
			Intent intent = new Intent();
			intent.setClass(DetailsView.this, SettingsActivity.class);
			startActivity(intent);
			break;

		default:
			break;
		}
		return false;
	}
	
	@Override
	protected void onPause() {
		mViewManager.showDetailViewBar(false);
		mViewManager.setTabBarVisibility(false);
		if ( !isShareViewShows ){
			mViewManager.setTitleBarVisibility(true);
		}
		mViewManager.setUserGuideVisibility(ImageButton.GONE);
		Log.i("onPause", "onPause");
		super.onPause();
	}  
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		mViewManager.setTitleBarVisibility(true);
		((RelativeLayout) findViewById(R.id.titlebar)).setVisibility(View.INVISIBLE);
		Log.i("onDestroy", "onDestroy");
	}  
	
	@Override
	public void onStop() {
		super.onStop();
		mViewManager.setTitleBarVisibility(true);
		((RelativeLayout) findViewById(R.id.titlebar)).setVisibility(View.INVISIBLE);
		Log.i("onDestroy", "onDestroy");
	}  
	
    /** 
     * 控制左右翻页和垂直滚动查看新闻
     */ 
	private View.OnTouchListener onTouchListener = new View.OnTouchListener() {

		public boolean onTouch(View v, MotionEvent event) {
			return gestureDetector.onTouchEvent(event);
		}
	};

	public class CommonGestureListener extends SimpleOnGestureListener {

		// 用户轻触触摸屏，由1个MotionEvent ACTION_DOWN触发    
		@Override
		public boolean onDown(MotionEvent e) {
			Log.d("QueryViewFlipper", "====> helei: do onDown...");
			isScrolling =false;
			return false;
		}

	    /*  
	     * 用户轻触触摸屏，尚未松开或拖动，由一个1个MotionEvent ACTION_DOWN触发  
	     * 注意和onDown()的区别，强调的是没有松开或者拖动的状态 (单击没有松开或者移动时候就触发此事件，再触发onLongPress事件)  
	     */
		@Override
		public void onShowPress(MotionEvent e) {
			Log.d("QueryViewFlipper", "====> helei: do onShowPress...");
			super.onShowPress(e);
		}

		 // 用户长按触摸屏，由多个MotionEvent ACTION_DOWN触发   
		@Override
		public void onLongPress(MotionEvent e) {
			Log.d("QueryViewFlipper", "----> helei: do onLongPress...");
		}

		
        /*  
         * 两个函数都是在Touch Down后又没有滑动(onScroll)，又没有长按(onLongPress)，然后Touch Up时触发  
         * 点击一下非常快的(不滑动)Touch Up: onDown->onSingleTapUp->onSingleTapConfirmed  
         * 点击一下稍微慢点的(不滑动)Touch Up://确认是单击事件触发  
         * onDown->onShowPress->onSingleTapUp->onSingleTapConfirmed  
         */
		@Override
		public boolean onSingleTapConfirmed(MotionEvent e) {
			Log.d("QueryViewFlipper", "====> helei: do onSingleTapConfirmed...");
			if (!mLoadingShowing) {
			toggleAnimfullScream();
		}
			return false;
		}

	    /** 
	     * 单击事件
	     * 用户（轻触触摸屏后）松开，由一个1个MotionEvent ACTION_UP触发
	     */ 
		@Override
		public boolean onSingleTapUp(MotionEvent e) {
			Log.d("QueryViewFlipper", "====> helei: do onSingleTapUp...");
//			if (!mLoadingShowing) {
//				toggleAnimfullScream();
//			}

			return false;
		}
		
	    /** 
	     * 新闻左右滑动翻页事件
	     *  
         * e1：第1个ACTION_DOWN MotionEvent    
         * e2：最后一个ACTION_MOVE MotionEvent    
         * velocityX：X轴上的移动速度，像素/秒    
         * velocityY：Y轴上的移动速度，像素/秒    
         *
         * 触发条件 ：    
         * X轴的坐标位移大于FLING_MIN_DISTANCE，且移动速度大于FLING_MIN_VELOCITY个像素/秒 
         * Touch了滑动一点距离后，up时触发  
	     *  
         * 用户按下触摸屏、快速移动后松开，由1个MotionEvent ACTION_DOWN, 多个ACTION_MOVE,  
         * 1个ACTION_UP触发(non-Javadoc)  
         * Fling事件的处理代码：除了第一个触发Fling的ACTION_DOWN和最后一个ACTION_MOVE中包含的坐标等信息外  
         * ，我们还可以根据用户在X轴或者Y轴上的移动速度作为条件  
         * 比如下面的代码中我们就在用户移动超过100个像素，且X轴上每秒的移动速度大于200像素时才进行处理。  
         *   
         * @see Android.view.GestureDetector.OnGestureListener#onFling(android.view.  
         * MotionEvent, Android.view.MotionEvent, float, float)  
         * 这个例子中，tv.setLongClickable( true )是必须的，因为  
         * 只有这样，view才能够处理不同于Tap（轻触）的hold（即ACTION_MOVE，或者多个ACTION_DOWN）  
         * ，我们同样可以通过layout定义中的Android:longClickable来做到这一点  
	     */ 
		@Override
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
				float velocityY) {
			if (Math.abs(e1.getY() - e2.getY()) < Math.abs(e1.getX()
					- e2.getX())&& ( !isScrolling == true )) {
				Log.i("QueryViewFlipper", "====> helei: do onFling...");
				if (e1.getX() - e2.getX() > 100 && Math.abs(velocityX) > 50
						&& !mLoadingShowing) {
					// 手势向左滑动查看下一页
					Log.i("DIS", "横向距离" + (e1.getX() - e2.getX()));
					Log.i("SPEED", "横向速度" + Math.abs(velocityX));
					if (FromType != FromFavoritesList) {
						previousbutton.setVisibility(View.VISIBLE);
					}
					HandleShowNextNews();


				} else if (e2.getX() - e1.getX() > 100
						&& Math.abs(velocityX) > 50) {
					// 手势向右滑动，查看上一页

					Log.i("SPEED", "横向速度1" + Math.abs(velocityX));
					Log.i("DIS", "横向距离1" + (e2.getX() - e1.getX()));
					if (FromType != FromFavoritesList) {
						nextbutton.setVisibility(View.VISIBLE);
					}
					HandleShowPreviousNews();


				}

			}
			return true;
		}
		
	    /** 
	     * 用户按下触摸屏，并拖动，由1个MotionEvent ACTION_DOWN, 多个ACTION_MOVE触发 
	     */ 
		@Override
		public boolean onScroll(MotionEvent e1, MotionEvent e2,
				float distanceX, float distanceY) {
			Log.i("QueryViewFlipper", "====> helei: do onScroll...");
			if (Math.abs(e1.getY() - e2.getY()) > 100
					&& !mLoadingShowing
					&& Math.abs(distanceY) > 10) {
//					&& (Math.abs(e1.getY() - e2.getY()) > Math.abs(e1.getX()
//							- e2.getX()))) {
				isScrolling = true;
				Log.i("QueryViewFlipper", "====> isScrolling");
				if (!mIsFullScreen)
					toggleAnimfullScream();
				return true;
			}else
			{
				return false;
			}
		}

	}
	
    /** 
     * 处理新闻阅读页阅读上一条新闻逻辑
     * 
     */ 
	public void HandleShowPreviousNews(){
		if (mPosition > 0) {
			mPosition = mPosition - 1;
			if (mPosition == 0) {
				// mViewManager.showPreButton(false);
				previousbutton.setVisibility(View.INVISIBLE);
			}
			ShowPreviousNews();
		}

		if (mGoalHiPosition > 0) {
			mGoalHiPosition = mGoalHiPosition - 1;
			if (mGoalHiPosition == 0) {
				// mViewManager.showPreButton(false);
				previousbutton.setVisibility(View.INVISIBLE);
			}
			ShowPreviousNews();
		}

		if (mF1Position > 0) {
			mF1Position = mF1Position - 1;
			if (mF1Position == 0) {
				// mViewManager.showPreButton(false);
				previousbutton.setVisibility(View.INVISIBLE);
			}
			ShowPreviousNews();
		}

		if (mHotClickPosition > 0) {
			mHotClickPosition = mHotClickPosition - 1;
			if (mHotClickPosition == 0) {
				// mViewManager.showPreButton(false);
				previousbutton.setVisibility(View.INVISIBLE);
			}
			ShowPreviousNews();
		}

		if (mHotClickPosition > 0) {
			mHotClickPosition = mHotClickPosition - 1;
			if (mHotClickPosition == 0) {
				// mViewManager.showPreButton(false);
				previousbutton.setVisibility(View.INVISIBLE);
			}
			ShowPreviousNews();
		}

		if (mSearchPosition > 0) {
			mSearchPosition = mSearchPosition - 1;
			if (mSearchPosition == 0) {
				// mViewManager.showPreButton(false);
				previousbutton.setVisibility(View.INVISIBLE);
			}
			ShowPreviousNews();
		}
		
	}
	
    /** 
     * 处理新闻阅读页阅读下一条新闻逻辑
     * 
     */ 
	public void HandleShowNextNews(){
		if (FromType == FromMainList
				&& mPosition < HomeView.mNewsList.size() - 1) {
			mPosition = mPosition + 1;
			if (mPosition == HomeView.mNewsList.size() - 1) {
				// mViewManager.showNextButton(false);
				nextbutton.setVisibility(View.INVISIBLE);
			}
			ShowNextNews();
		}
		
	}
	
    /** 
     * 切换到上一条新闻
     * 
     */ 
	public void ShowPreviousNews() {
		//修复Monkey Testing viewFlipper空指针异常
		if ( viewFlipper == null ){
			viewFlipper = (ViewFlipper) findViewById(R.id.viewflipper_data);
		}
		viewFlipper.addView(getContentView());
		viewFlipper.setInAnimation(AnimationControl.inFromLeftAnimation());
		viewFlipper.setOutAnimation(AnimationControl.outToRightAnimation());
		viewFlipper.showNext();
		viewFlipper.removeViewAt(0);
	}
	
    /** 
     * 切换到下一条新闻
     * 
     */ 
	public void ShowNextNews() {
		//修复Monkey Testing viewFlipper空指针异常
		if ( viewFlipper == null ){
			viewFlipper = (ViewFlipper) findViewById(R.id.viewflipper_data);
		}
		viewFlipper.addView(getContentView());
		viewFlipper.setInAnimation(AnimationControl.inFromRightAnimation());
		viewFlipper.setOutAnimation(AnimationControl.outToLeftAnimation());
		viewFlipper.showNext();
		viewFlipper.removeViewAt(0);
	}

}
